import React from 'react';
import {
  Table,
  Input,
  Select,
  Button,
  message,
} from 'antd';
import axios from 'axios';
import intercept from '../../../utils/intercept';
import { config } from 'utils';
import '../less/Rent.less';
import format from './format';
import { Map, Markers } from 'react-amap';
const styleA = {
  background: `url('http://218.28.27.171:9011/images/pmbackend/car.png')`,
  backgroundSize: 'contain',
  backgroundRepeat: 'no-repeat',
  backgroundPosition: 'center',
  width: '40px',
  height: '50px',
} 

const Option = Select.Option;
class RentStart extends React.Component {
  constructor(props) {
    super(props);
    // 地图
    this.markersEvents = {
      created: (allMarkers) => {
        allMarkers.forEach(function (item, i) {
          item.setLabel({//label默认蓝框白底左上角显示，样式className为：amap-marker-label{format.format(record.rentalTime)}
            content: `<div style="padding: 4px 5px;"><p style="text-align: center;font-size:17px;font-weight: 500;color:black">${item.B.extData.message.isSharing ? '拼车' : '包车'}<p/><p style="padding:6px 0;"><span style="color:#8E8E8E">出发地：</span><span style="color:black;font-weight: 500;font-size:15px;">${item.B.extData.message.startPlaceDetail}</span></p><p><span style="color:#8E8E8E">目的地：</span><span style="color:black;font-weight: 500;font-size:15px;">${item.B.extData.message.endPlaceDetail}</span></p><p style="margin-top:5px;"><span style="color:#8E8E8E">约车时间：</span><span style="color:black;font-weight: 500;font-size:15px;">${format.format(item.B.extData.message.rentalTime)}</span></p></div>`,
            offset: (20, -20)
          });
        });
      },
      click: (MapsOption, marker) => {
        this.setState({
          modalData: marker.B.extData.message,
          mapCenter: marker.B.extData.position
        });
        if (this.state.selectedRowKeys.indexOf(marker.B.extData.message.orderCode) < 0) {
          this.state.selectedRowKeys.push(marker.B.extData.message.orderCode);
          message.success(`添加成功：${marker.B.extData.message.orderCode}`);
          this.setState({ selectedRowKeys: this.state.selectedRowKeys })
        } else {
          this.state.selectedRowKeys.splice(this.state.selectedRowKeys.indexOf(marker.B.extData.message.orderCode), 1)
          message.success(`取消选择：${marker.B.extData.message.orderCode}`)
          this.setState({ selectedRowKeys: this.state.selectedRowKeys })
        }
      },
      //dragend: (MapsOption, marker) => { /* ... */ }
    }
    this.state = {
      selectedRowKeys: [],
      dataSource: [],
      loading: false,
      drivers: [],
      car: [],
      pagination: {
        current: 1,
        pageSize: 10
      },
      onChange: this.onChange,
      keyword: '',
      orderData: {},
      // 地图数据
      // markers: [],
      icon: "../../image/vehicle.png",
      // 地图显示控制
      mapTrue: true,
      // 地图车辆位置显示控制
      // startingPosition: true

    }
  }

  // 地图
  mapTrueFun = () => {
    this.setState({ mapTrue: !this.state.mapTrue })
  }
  renderMarker(extData) {
    return <div style={styleA}></div>
  }

  onChange = (pagination, filters, sorter) => {
    this.GetSendOrders({
      sortField: sorter.field,
      sortOrder: sorter.order,
      page: pagination.current,
      keyword: this.state.keyword,
      ...filters
    });
  };
  search(value) {
    this.setState({ keyword: value });
    this.GetSendOrders({ keyword: value });
  }

  // 派车
  depart = () => {
    const token = sessionStorage.getItem("token");
    axios.post(`${config.api}Rental/SendOrders`, { orderCode: this.state.selectedRowKeys, deriverid: this.deriverid, carid: this.carid }, { headers: { Authorization: 'Bearer ' + token } }).then((data) => {
      if (data.data.result) {
        this.GetSendOrders();
        message.success('分派车辆成功！');
        // this.orderListDelete(this.state.selectedRowKeys);
      } else {
        message.warning(data.data.errorMessage);
      }
    })
    .catch(err => {
      intercept;
    })
  }
  // 派车成功后将成功定单从列表中删除
  orderListDelete(order) {
    let DdataSource = this.state.dataSource;
    let Dmarkers = this.state.markers;
    // 从表格中删除
    for (let i = 0; i < DdataSource.length; i++) {
      if (DdataSource[i].orderCode == order) {
        DdataSource.splice(DdataSource[i], 1)
      }
    }
    // 地图上删除
    for (let j = 0; j < Dmarkers.length; j++) {
      if (Dmarkers[j].message.orderCode == order) {
        Dmarkers.splice(Dmarkers[j], 1)
      }
    }
    this.setState({ dataSource: DdataSource, markers: Dmarkers })
  }
  onSelectChange = (selectedRowKeys) => {
    this.setState({ selectedRowKeys });
    this.state.selectedRowKeys.push(selectedRowKeys)
  }

  componentDidMount() {
    this.GetSendOrders();
    this.GetDriverInfo();
    this.GetCarInfo();
  };
  driverChange = (value) => {
    this.deriverid = value;
  }
  carChange = (value) => {
    this.carid = value;
  }

  // 司机信息
  GetDriverInfo = (params = {}) => {
    let that = this;
    const token = sessionStorage.getItem("token");
    axios.get(`${config.api}Rental/GetDriverInfo`, { headers: { Authorization: 'Bearer ' + token } }).then((data) => {
      data.data.drivers.forEach(function (item) {
        that.state.drivers.push(
          <Option key={item.id}>{item.driverName}</Option>
        )
      })
    })
    .catch(err => {
      intercept;
    })
  }
  // 车辆信息
  GetCarInfo = () => {
    let that = this;
    const token = sessionStorage.getItem("token");
    axios.get(`${config.api}Rental/GetCarInfo`, { headers: { Authorization: 'Bearer ' + token } }).then((data) => {
      // console.log(data)
      data.data.cars.forEach((item) => {
        that.state.car.push(
          <Option key={item.carId}>{item.plateNum}</Option>
        )
      })
    })
    .catch(err => {
      intercept;
    })
  }
  // 处理显示车辆显示位置，布尔值控制始发/目的地显示
  classify(data, boolean) {
    try {
      let positionArr = new Array();
      var collections = data.data.pageList.collections;
      for (let i = 0; i < collections.length; i++) {
        if (collections[i].startCoordinate && collections[i].endCoordinate) {
          positionArr.obj = new Object();
          positionArr.obj.position = new Object();
          positionArr.obj.position.longitude = boolean ? collections[i].startCoordinate.split(",")[0] : collections[i].endCoordinate.split(",")[0];
          positionArr.obj.position.latitude = boolean ? collections[i].startCoordinate.split(",")[1] : collections[i].endCoordinate.split(",")[1];
          positionArr.obj.message = collections[i];
          positionArr.push(positionArr.obj);
        }
      }
      let dataArry = [];
      for(let j = 0; j < positionArr.length; j++){
        if(isNaN(positionArr[j].position.longitude) || isNaN(positionArr[j].position.latitude) == false){
          dataArry.push(positionArr[j])
        }
      }
      return dataArry
    } catch (err) {
      console.log(err)
    }
  }

  // 待分派订单
  async GetSendOrders(params = {}) {
    this.setState({ loading: true });
    let that = this;
    const token = sessionStorage.getItem("token");
    let keyword = typeof (params.keyword) === "undefined"
      ? ''
      : params.keyword;
    axios.get(`${config.api}Rental/GetSendOrders?page=${params.page}&pageSize=${this.state.pagination.pageSize}keyword=${keyword}`, { headers: { Authorization: 'Bearer ' + token } }).then((data) => {
      // console.log(data)
      const pagination = {
        ...this.state.pagination
      };

      pagination.total = data.data.pageList.totalRows;
      pagination.current = params.page;
      this.setState({ loading: false, dataSource: data.data.pageList.collections, pagination, markers: this.classify(data), orderData: data });
    })
    .catch(err => {
      intercept;
    })
  }

  isState(state) {
    if (state == 1) {
      return '待分配'
    } else {
      return '已撤销'
    }
  }
  render() {
    const Search = Input.Search;
    const columns = [{
      title: '订单号',
      dataIndex: 'orderCode',
    }, {
      title: '类型',
      dataIndex: 'isSharing',
      render: (text, record) => {
        return (
          <span>{record.isSharing ? '拼车' : '包车'}</span>
        )
      }
    }, {
      title: '约租时间',
      dataIndex: 'rentalTime',
      render: (text, record) => {
        return (
          <span>{format.format(record.rentalTime)}</span>
        )
      }
    }, {
      title: '出发地',
      dataIndex: 'startPlaceDetail',
    }, {
      title: '线路',
      dataIndex: 'companyCode',
    }, {
      title: '人数',
      dataIndex: 'passengerAccount',
    }, {
      title: '价格(元)',
      dataIndex: 'originalTotalPrice',
    }, {
      title: '订单状态',
      dataIndex: 'orderStatus',
      render: (text, record) => {
        return (
          <span>{this.isState(record.orderStatus)}</span>
        )
      }
    }];
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      // hideDefaultSelections: true,
      // selections: [{
      //   key: 'all-data',
      //   text: '选择所有',
      //   onSelect: () => {
      //     this.setState({
      //       selectedRowKeys: [...this.state.dataSource.keys()], // 0...45
      //     });
      //   },
      // }],
      onSelection: this.onSelection,
    };
    return (
      <div className="pack">
        <div className="priming">
          <Search
            placeholder="请输入任意查询条件"
            style={{
              width: 500
            }}
            onSearch={value => this.search(value)} />

          <span className="choose">
            <Select
              showSearch
              style={{ width: 200 }}
              placeholder="请选择司机"
              optionFilterProp="children"
              onChange={this.driverChange}
              filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
            >
              {this.state.drivers}
            </Select>

            <Select className="car"
              showSearch
              style={{ width: 200 }}
              placeholder="请选择车辆"
              optionFilterProp="children"
              onChange={this.carChange}
              filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
            >
              {this.state.car}
            </Select>
            <Button type="primary" onClick={this.depart}>派车</Button>
            <span onClick={this.mapTrueFun} style={{ color: '#108EE9', float: 'right', cursor: 'pointer' }}>{this.state.mapTrue ? '隐藏地图' : '显示地图'}</span>
          </span>

          {this.state.mapTrue ? <div style={{margin: '15px 0'}}>
            <div style={{ textAlign: 'center', color: '#8E8E8E', marginTop: '5px', fontSize: '15px' }}><span>点击地图车辆位置图标可以直接选点</span><div style={{ float: 'right' }}>
              <Button style={{ marginRight: '10px' }} onClick={() => this.setState({ markers: this.classify(this.state.orderData, true) })}>车辆始发点位置</Button>
              <Button onClick={() => this.setState({ markers: this.classify(this.state.orderData, false) })}>车辆目的地位置</Button>
            </div>
            </div> </div>
            : ''}

        </div>
        {/* 地图 */}
        {this.state.mapTrue && this.state.markers ? (<div style={{ width: '100%', height: 450 }}>
          <Map plugins={['ToolBar']} center={this.state.mapCenter} zoom={6} amapkey={'e27baa748ea19c268dd6a6218f1c85a4'} >
            <Markers
              markers={this.state.markers}
              events={this.markersEvents}
              // render={this.renderMarker}
            >
            </Markers>
          </Map>
        </div>) : ''}

        <Table
          {...this.state}
          className="RentStartTable"
          rowKey={record => record.orderCode}
          rowSelection={rowSelection}
          columns={columns}
        />
      </div>
    )
  }
}

export default RentStart
